<!--
 * @Author: 107w 8801453+lu-shangru@user.noreply.gitee.com
 * @Date: 2023-10-17 14:37:10
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2023-11-16 11:15:52
 * @Description:
 *
 * Copyright (c) 2023 by 107w, All Rights Reserved.
-->
<template>
  <el-dialog
    :title="`用户【${currUser.userName}】终端分配`"
    :visible.sync="permissionVisibleProxy"
    width="800px"
  >
    <div v-loading="loading" class="permisson_wrap">
      <div class="permisson_item">
        <div class="header">
          <span>文件列表</span>
          <el-checkbox @change="selectAllDirectory">全选</el-checkbox>
        </div>
        <div class="content">
          <el-tree
            ref="tree"
            :data="allTreeTerminal"
            default-expand-all
            :check-strictly="checkStrictly"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            @check-change="handleCheckChange"
          />
        </div>
      </div>
      <div class="icon_right">
        <i
          style="font-size: 40px; color: #ccc; margin: 0 16px"
          class="iconfont icon-tiaozhuan1"
        />
      </div>
      <div class="permisson_item">
        <div class="header">
          <span>终端列表</span>
          <el-checkbox @change="selectAllTerminal">全选</el-checkbox>
        </div>
        <div class="content">
          <div
            v-for="dtRelation in dtRelationList"
            :key="dtRelation.directoryId"
            class="directory_item"
          >
            <div class="directory_name">{{ dtRelation.directoryName }}</div>
            <el-checkbox-group
              v-if="dtRelation.terminalList.length > 0"
              v-model="dtRelation.terminalIdList"
            >
              <el-checkbox
                v-for="item in dtRelation.terminalList"
                :key="item.terminalId"
                :label="item.terminalId"
              >{{ `${item.hostName}(${item.hostIp})` }}</el-checkbox>
            </el-checkbox-group>
            <div v-else style="text-align: center">暂无数据</div>
          </div>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button
        size="small"
        @click="permissionVisibleProxy = false"
      >取 消</el-button>
      <el-button
        type="primary"
        size="small"
        @click="relationAdd"
      >确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getRelationByUserId, relationAdd } from '@/api/directory'
export default {
  name: 'AssignPermissions',
  props: {
    currUser: {
      type: Object,
      default: () => ({})
    },
    permissionVisible: {
      type: Boolean
    },
    allTreeTerminal: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: true,
      treeData: [],
      checkStrictly: true, // 树形控件父子关联与否
      defaultProps: {
        children: 'childList',
        label: 'directoryName'
      },
      initDataTime: '',
      dtRelationList: []
      // dtRelationList: [
      //   {
      //     directoryId: 0,
      //     directoryName: '目录1-1',
      //     terminalList: [
      //       { terminalId: 1, hostName: '测dwa试1', hostIp: '127.02.3.1' },
      //       { terminalId: 2, hostName: '测试1', hostIp: '127.02.3.1' },
      //       { terminalId: 3, hostName: '测带娃打完试1', hostIp: '127.02.3.1' },
      //       { terminalId: 4, hostName: '测试1', hostIp: '127.02.3.1' }
      //     ],
      //     terminalIdList: []
      //   },
      // ]
    }
  },
  computed: {
    // 代理permissionVisible，触发修改相应set函数
    permissionVisibleProxy: {
      get() {
        return this.permissionVisible
      },
      set(val) {
        this.$emit('update:permissionVisible', val)
      }
    }
  },
  async mounted() {
    await this.getRelationByUserId()
  },
  methods: {
    initData(dtRelationList) {
      this.initDataTime = Date.now()
      if (!dtRelationList) {
        this.loading = false
        return
      }
      // 左侧目录列表回显
      const directoryIdList = dtRelationList.map((item) => item.directoryId)
      this.$refs['tree'].setCheckedKeys(directoryIdList ?? [])
      // this.checkStrictly = false
      // 右侧终端列表回显
      const checkedNodes = this.$refs['tree'].getCheckedNodes()
      this.dtRelationList = checkedNodes.map((dtRelation) => {
        const directory = dtRelationList.find(item => item.directoryId === dtRelation.id)
        return {
          directoryId: dtRelation.id,
          directoryName: dtRelation.directoryName,
          terminalList: dtRelation.terminalList ?? [],
          terminalIdList: directory.terminalIdList ?? []
        }
      })
      this.loading = false
    },
    async getRelationByUserId() {
      try {
        const params = {
          userId: this.currUser.id
        }
        const res = await getRelationByUserId(params)
        if (res.success) {
          this.initData(res.result.dtRelationList)
        }
      } catch (error) {
        console.log(error)
      }
    },
    async relationAdd() {
      try {
        const dtRelationList = this.dtRelationList.map(item => ({
          directoryId: item.directoryId,
          terminalIdList: item.terminalIdList
        }))
        const params = {
          userId: this.currUser.id,
          dtRelationList
        }
        const res = await relationAdd(params)
        if (res.success) {
          this.$message.success(`用户【${this.currUser.userName}】的终端权限配置成功`)
          this.permissionVisibleProxy = false
        }
      } catch (error) {
        console.log(error)
      }
    },
    handleCheckChange(currNode, checked) {
      // 消除回显带来的事件触发
      if (Date.now() - this.initDataTime < 100) {
        return
      }
      const findNode = this.dtRelationList.find(item => item.directoryId === currNode.id)
      if (!findNode && checked) {
        this.dtRelationList.push({
          directoryId: currNode.id,
          directoryName: currNode.directoryName,
          terminalList: currNode.terminalList ?? [],
          terminalIdList: []
        })
      } else if (findNode && !checked) {
        this.dtRelationList = this.dtRelationList.filter(item => item.directoryId !== currNode.id)
      }
    },
    // 终端列表全选事件
    selectAllTerminal(isSelect) {
      // console.log(isSelect)
      if (isSelect) {
        this.dtRelationList.forEach(item => {
          item.terminalIdList = item.terminalList.map(terminal => terminal.terminalId)
        })
      } else {
        this.dtRelationList.forEach(item => {
          item.terminalIdList = []
        })
      }
    },
    // 文件列表全选
    selectAllDirectory(isSelect) {
      if (isSelect) {
        this.checkStrictly = false
        this.$nextTick(() => {
          this.$refs.tree.setCheckedNodes(this.allTreeTerminal)
          this.checkStrictly = true
        })
      } else {
        this.$refs.tree.setCheckedKeys([])
      }
      // 全选

      // this.$refs.tree.setCheckedKeys([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

      // 清空
      // this.$refs.tree.setCheckedNodes([]);
      // this.$refs.tree.setCheckedKeys([])
    }
  }
}
</script>

<style lang="scss" scoped>
.permisson_wrap {
  display: flex;
  align-items: center;
}
.permisson_item {
  width: 340px;
  height: 500px;
  border: 1px solid #d8dce5;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  .header {
    padding: 0 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    background-color: #eff1f5;
  }
  .content {
    padding: 10px 16px;
    flex: 1;
    overflow-y: scroll;
  }
  .el-checkbox-group {
    margin-left: 16px;
    display: flex;
    flex-direction: column;
    .el-checkbox {
      margin: 10px 0;
    }
  }
}
.directory_item {
  padding: 10px;
  border-top: 1px solid #ebe8e8;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 1px 1px hsl(0deg 0% 0% / 0.075),
    0 2px 2px hsl(0deg 0% 0% / 0.075), 0 4px 4px hsl(0deg 0% 0% / 0.075),
    0 8px 8px hsl(0deg 0% 0% / 0.075);
}
</style>
